import {
    printImage,
    sendDataToDevice,
    overwriteImageData,
    printQR,
    printCommand,
} from '../../wx-weapp-tool/bluetoolth';

import GBK from '../../wx-weapp-tool/libs/gbk.min';

import getBluetoothPageConfig from '../../wx-weapp-tool/bluetoothConnectionTemplate/index';
const bluetoothConfig = getBluetoothPageConfig();
const constant = require("../../util/constant.js");
const util = require('../../util/util.js');
const app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    ColorList: app.globalData.ColorList,
    ...bluetoothConfig.data,
        // 打印机纸张宽度，我用的打印几的纸张最大宽度是384，可以修改其他的
        paperWidth: 284,
        canvasWidth: 1,
        canvasHeight: 1,
        img: '',
        threshold: [200],
        percentage: 0,
        printing: false,
        corpname:'',
        corpno:'',
        corpcity:'',
        corpaddress:'',
        corplink:'',
        corpbank:'',
        printing: false,
        bankno:'',
        /*
        message: `            郑州市市城市综合执法局
                                当场处罚决定书
                        郑城综当罚决字〔2022〕第2201012号 
        当事人姓名：获取当事人姓名
        年龄：获取当事人年龄
        你（单位）于___年___月___日___时___分在___________________因____________________________的行为，违反了__________________________________的规定，有证据___________________
        现责令你（单位）于_______年______月______日    _______时前自行__________________________                    
        现依据___________________________的规定、本局决定对你（单位）处以下行政处罚：                    
        警告；
        罚款人民币伍拾元整。￥:【50元】 缴纳罚款方式：
        当场收缴。（依据《中华人民共和国行政处罚法》第四十七条、第四十八条的规定）
        自收到本决定书之日起15日内将）罚款交至____银行（账  号：                  )。逾期未缴纳罚款的，可以每日按罚款数额的3%加处罚款。
        本局执法人员当场向你（单位）告知了违法事实、依据和依法享有的权利。陈述申辩情况：                                                          
        我于___年___月___日收到本处罚决定书、执法人员在处罚前已向我告知了权利，并听取了我的陈述和申辩。
        送达方式：___________________________________
        当事人签名：
        年     月      日`,
        */
       message: ``,
        checked: true,
    ND:'',
    AJBH:'',
    dsrhmtitle:'身份证号',
    dsr:'',
    dsrzjhm:'',
    dsrzhusuo:'',
    aftime:'',
    afdd:'',
    ay:'',
    wfl:'',
    cfyj:'',
    gzdes:'',
    cfdes:'',
    fkdes:'',
    jkhd:false,
    pjbh:'',
    zbr:'',
    zbrbh:'',
    xbr:'',
    xbrbh:'',
    jadate:'',
    deviceId:''
  },
  onHide() {
    bluetoothConfig.onHide.call(this);
    },
  onLoad: function (option) { 
    bluetoothConfig.onLoad.call(this, option);
    var mycorpname=wx.getStorageSync('cname');
    var mycorpno=wx.getStorageSync('cno');
    var mycorpcity=wx.getStorageSync('ccity');
    
    this.setData({
        corpname:mycorpname,
        corpno:mycorpno,
        corpcity:mycorpcity,
    })
    var mycorpaddress=wx.getStorageSync('caddr');
    var mycorplink=wx.getStorageSync('clink');
    var mycorpbank=wx.getStorageSync('cbank');
    var mybankno=wx.getStorageSync('bankno');
    
      var aid=option.aid;
      var myview="";
      var aywfl='';
      var aycfyj='';
      if(aid>0)
      {
       
        var that=this;
        wx.request({
            url: constant.host+'/appserv/getjz.ashx',
            data: {
              aid:aid,
              k: constant.wkey
            },
            success: function (data) {
            
              var dat = data.data;
              if(dat.length>0)
              {
 
                  var mydata=dat[0];
                  var ayid=mydata.AYID;
                  wx.request({
                    url: constant.host+'/appserv/getay.ashx',
                    data: {
                      aid:ayid,
                      k: constant.wkey
                    },
                    success: function (dataa) {
                        
                      var datt = dataa.data;
                      if(datt.length>0)
                      {
                          
                       let aydata=datt[0];
                       let isp=mydata.IsPerson;
                  let dsrhm="";
                  if(isp>0)
                  {
                      dsrhm="身份证号";
                  }
                  else
                  {
                      dsrhm="统一社会信用代码";
                  }
                  let ajtime=util.formatTimeToC(mydata.AFDate);
                  let zlgzst=mydata.AZLStat;
                  let cfst=mydata.ACFStat;
                  let fkst=mydata.AFKStat;
 
                  let lxfstitle="";
                  let jkhd=true;
                  if(cfst>0)
                  {
        
                      jkhd=false;
                      lxfstitle="罚款的履行方式和期限：";
                  }
                  let cfdes="";
                  if(fkst>0)
                  {
                      cfdes=mydata.AJFKFS+"。到期不缴纳罚款的，根据《中华人民共和国行政处罚法》第五十一条的规定，每日按罚款数额的百分之三加处罚款。"
                  }
                  else
                  {
                    cfdes=mydata.AJFKFS+"。";
                  }
                  let afdt=util.formatTimeToC(mydata.AFDate);
                  let gzdt="";
                  if(mydata.AZLGZDate!=null && mydata.AZLGZDate.length>0)
                  {
                      gzdt=mydata.AZLGZDate;
                  }
                  let fkdt="";
                  if(mydata.AFKDate!=null && mydata.AFKDate.length>0)
                  {
                      fkdt=mydata.AFKDate;
                  }
                  //console.log(mycorpname);
                  let myxbbh=mydata.XBRBH;
myview=`              `+mycorpname+`
               当场处罚决定书
    `+mycorpno+`城综当罚决字〔`+mydata.ND+`〕第`+mydata.BH+`号

当事人：`+mydata.DSR+`
`+dsrhm+`：`+mydata.DSRHM+`
住所（地址）：`+mydata.DSRAddress+`

    你（单位）于`+ajtime+`在`+mydata.AFAddress+`因`+mydata.AY+`的行为，违反了`+aydata.ayViolation+`的规定，根据`+aydata.ayAccording+`的规定，本机关责令你（单位）`+mydata.AJGZDes+`,并对你（单位）做出如下处罚：                    
`+mydata.AJCFDes+`
`+lxfstitle+`
    `+cfdes+`
    如不服本处罚决定，可在收到本决定书之日起60日内向`+mycorpcity+`市人民政府申请行政复议；也可在收到本决定书之日起6个月内向`+mycorpcity+`市人民法院提起行政诉讼，但本决定书不停止执行，法律另有规定的除外。逾期不申请行政复议、不提起行政诉讼又不履行的，本机关将依法申请人民法院强制执行或依照有关规定强制执行。                                                          
    本处罚决定书做出前已依法告知你（单位）作出处罚决定的事实、理由及依据，并听取了你（单位）的陈述和申辩。
    
    行政执法人员：`+mydata.ZBR+`
    执法证号：`+mydata.ZBRBH+`
    行政执法人员：`+mydata.XBR+`
    执法证号：`+mydata.XBRBH+`
    当事人签名：             日期：

              `+mycorpname+`（签章）
                     `+mydata.JADate;
//console.log(myview);
                  that.setData({
                      ajid:aid,
                      ND:mydata.ND,
                      AJBH:mydata.BH,
                      dsr:mydata.DSR,
                      dsrhmtitle:dsrhm,
                      dsrzjhm:mydata.DSRHM,
                      dsrzhusuo:mydata.DSRAddress,
                      aftime:ajtime,
                      afdd:mydata.AFAddress,
                      ay:mydata.AY,
                      gzdes:mydata.AJGZDes,
                      cfdes:mydata.AJCFDes,
                      fkdes:cfdes,
                      jkhd:jkhd,
                      pjbh:mydata.AJCFPJH,
                      zbr:mydata.ZBR,
                      zbrbh:mydata.ZBRBH,
                      xbr:mydata.XBR,
                      xbrbh:mydata.XBRBH,
                      jadate:mydata.JADate,
                      message:myview,
                      wfl:aydata.ayViolation,
                      cfyj:aydata.ayAccording
                  })
      
                      }
                      
                    }
                  });
                  
              }
              
            }
          });
      }

      const ctx = wx.createCanvasContext('secondCanvas');
      let tempFilePath='https://zyzfj.114jcw.com/img/zyzfjz.png'
      wx.getImageInfo({
          src: tempFilePath,
          success: (res) => {
              
          var path = res.path;
          //console.log("图片新路径")
          //console.log(path);
              // 打印宽度须是8的整数倍，这里处理掉多余的，使得宽度合适，不然有可能乱码
              const mw = this.data.paperWidth % 8;
              const w = mw === 0 ? this.data.paperWidth : this.data.paperWidth - mw;
              // 等比算出图片的高度
              const h = Math.floor((res.height * w) / res.width);
              
              // 设置canvas宽高
              this.setData({
                  img: path,
                  canvasHeight: h,
                  canvasWidth: w,

              });
              // 在canvas 画一张图片
              ctx.fillStyle = 'rgba(255,255,255,1)';
              ctx.clearRect(0, 0, w, h);
              ctx.fillRect(0, 0, w, h);
              ctx.drawImage(path, 0, 0, w, h);
              ctx.draw(false, () => {
                  wx.hideLoading();
              });
          /*
              setTimeout(() => {
                  this.printImage()
                  },200)*/
          },
          fail: (res) => {
              console.log('get info fail', res);
              wx.hideLoading();
          },
      });  
      
  },
  pageBack() {
    wx.navigateBack({
      delta: 1
    });
  },
  printtImage() {
    if (!this.data.deviceId) {
        wx.showToast({
            title: '未连接任何蓝牙设备',
            icon: 'none',
        });
        return;
    }
    if (this.lock === true) {
        console.log('lock');
        return;
    }
    this.lock = true;
    // 选择一张图片
    const { img } = this.data;
    console.log("要打印的图片")
    console.log(img);
    console.log(this.data);
    if (!img) {
        wx.showToast({
            title: '未获取图片',
            icon: 'none',
        });
        this.lock = false;
        return;
    }
    const { canvasWidth, canvasHeight, deviceId, threshold } = this.data;
    console.log('threshold', threshold);
    //获取画布里的图片数据sss
    wx.canvasGetImageData({
        canvasId: 'secondCanvas',
        x: 0,
        y: 0,
        width: canvasWidth,
        height: canvasHeight,
        success: (res) => {
            const pix = res.data;
            console.log("pix")
            console.log(pix);
            const opt = {
                deviceId,
                ...this.character,
                onProgress: (percentage) => {
                    console.log('percentage', percentage);
                    this.setData({
                        percentage,
                    });
                },
                lasterSuccess: () => {
                    console.log('laster success');
                    this.setData({
                        printing: false,
                        percentage: 0,
                    });
                    wx.showModal({
                        title: '提示',
                        content: '数据已发送完，请检查打印的内容是否正常',
                        showCancel: false,
                        confirmText: '好的',
                    });
                },
            };
            this.setData({
                printing: true,
            });
            //打印图片
            printImage(
                opt,
                // 将图片数据转成位图数据
                overwriteImageData({
                    threshold: threshold[0],
                    imageData: pix,
                    width: canvasWidth,
                    height: canvasHeight,
                }),
            );
        },
        complete: () => {
            this.lock = false;
        },
    });
},
  onUnload() {
    bluetoothConfig.onUnload.call(this);
    },
    onPullDownRefresh() {
        bluetoothConfig.onPullDownRefresh.call(this);
    },
    ...bluetoothConfig.methods,
  doprint(e){
    
       /*
      var that=this;
    wx.openBluetoothAdapter({//初始化蓝牙
        success: function (res) {
          wx.getBluetoothAdapterState({//获取本机蓝牙适配器状态。
            success: function (res) {
              if (res.available) {//蓝牙适配器是否可用
               //下一步操作
               wx.startBluetoothDevicesDiscovery({//搜索附近的蓝牙设备
                services: [],//筛选过滤搜索的蓝牙设备
                success(res) {
                  setTimeout(() => {
                    wx.getBluetoothDevices({//获取蓝牙列表
                      services: [],
                      success: function (res) {
                        //callback(res);//返回蓝牙列表
                       
                        var dat=res.devices;
                        //console.log(res);
                        //console.log(dat);
                        var dvid="";
                        for(var i=0;i<dat.length;i++)
                        {
                            //console.log(dat[i].name);
                            if(dat[i].name=="H98")
                            {
                                dvid=dat[i].deviceId;
                            }
                        }
                        console.log(dvid);
                        that.setData({
                            deviceId:dvid
                        })
                      },
                      fail(res) {
                        wx.showModal({
                          title: '提示',
                          content: '获取蓝牙设备列表失败',
                        })
                      }
                    })
                  }, 2000)
                  //关闭搜索
                  wx.stopBluetoothDevicesDiscovery({
                    success: function (res) {}
                  })
                }
              })         
              } else {
                wx.showModal({
                  title: '提示',
                  content: '本机蓝牙不可用',
                })
              }
            }
          })
        },
        fail: function () {
          wx.showModal({
            title: '提示',
            content: '蓝牙初始化失败，请打开蓝牙',
          })
        }
      }) */
      //console.log('获取的设备信息'+this.data.deviceId);
      if (!this.data.deviceId) {
        wx.showToast({
            title: '未连接任何蓝牙设备',
            icon: 'none',
        });
        return;
        
    }
    //console.log("did:"+this.data.devices[0].devId);
    //const opt = { deviceId: this.data.devices[0].devId, ...this.character };
    const opt = { deviceId: this.data.devices[0].devId, ...this.character };
    //console.log(...GBK.encode(this.data.message));
    sendDataToDevice({
        ...opt,
        value: new Uint8Array([...printCommand.clear, ...GBK.encode(this.data.message), ...printCommand.enter])
            .buffer,

        lasterSuccess: () => {
          this.printtImage();
            //console.log('打印')
            // 用指令打印二维码
            //if (this.data.checked) {
                /*
                printQR({
                    ...opt,
                    value: new Uint8Array(GBK.encode('https://www.baidu.com/')).buffer,
                });
                */
            //}
        },
    });     
  }
});
